package com.lagou.sqlsession;

import com.lagou.config.Configuration;
import com.lagou.mapping.BoundSql;
import com.lagou.mapping.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SimpleExecutor implements Executor {
    private Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> query(MappedStatement mappedStatement, Object... params) throws Exception {
        System.out.println("执行查询方法");

        Connection connection = configuration.getDataSource().getConnection();

        String orgSql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(orgSql);
        String sql = boundSql.getSql();
        System.out.println("sql:"+ sql);
        System.out.println("param:"+ Arrays.toString(params));
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null){
            Class<?> parameterTypeClass = getClassType(mappedStatement.getParameterType());

            int paramSize = parameterMappings.size();
            boolean customType = isCustomType(parameterTypeClass);

            for (int i = 0; i < paramSize; i++) {
                ParameterMapping mapping = parameterMappings.get(i);
                Object o = null;
                if (customType){
                    //自定义类型，则取属性值
                    String fieldName = mapping.getContent();
                    Field declaredField = parameterTypeClass.getDeclaredField(fieldName);
                    declaredField.setAccessible(true);
                    o = declaredField.get(params[0]);
                }else {
                    //否则直接取参数值
                    o = params[0];
                }

                preparedStatement.setObject(i+1, o);
            }
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        List<Object> objects = getResultObjects(resultSet,mappedStatement);
        return (List<E>) objects;
    }


    @Override
    public int update(MappedStatement mappedStatement, Object... params) throws Exception {
        System.out.println("执行查询方法");

        Connection connection = configuration.getDataSource().getConnection();

        String orgSql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(orgSql);
        String sql = boundSql.getSql();
        System.out.println("sql:"+ sql);
        System.out.println("param:"+ Arrays.toString(params));
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null){
            Class<?> parameterTypeClass = getClassType(mappedStatement.getParameterType());

            int paramSize = parameterMappings.size();
            boolean customType = isCustomType(parameterTypeClass);

            for (int i = 0; i < paramSize; i++) {
                ParameterMapping mapping = parameterMappings.get(i);
                Object o = null;
                if (customType){
                    //自定义类型，则取属性值
                    String fieldName = mapping.getContent();
                    Field declaredField = parameterTypeClass.getDeclaredField(fieldName);
                    declaredField.setAccessible(true);
                    o = declaredField.get(params[0]);
                }else {
                    //否则直接取参数值
                    o = params[0];
                }

                preparedStatement.setObject(i+1, o);
            }
        }

        int i = preparedStatement.executeUpdate();
        return i;
    }

    /**
     * 简单的判断是否自定义类型，不严谨
     * @param parameterTypeClass
     * @return
     */
    private boolean isCustomType(Class<?> parameterTypeClass){
        if (parameterTypeClass == null){
            return false;
        }
        if (parameterTypeClass.isPrimitive()){
            return false;
        }
//        if (parameterTypeClass.isAssignableFrom(Number.class)){
        if (Number.class.isAssignableFrom(parameterTypeClass)){
            return false;
        }
        if (String.class.equals(parameterTypeClass)){
            return false;
        }
        return true;
    }

    private List<Object> getResultObjects(ResultSet resultSet, MappedStatement mappedStatement) throws Exception {
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        List<Object> objects = new ArrayList<>();
        while (resultSet.next()){
            Object instance = resultTypeClass.getDeclaredConstructor().newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance,value);

            }
            objects.add(instance);
        }
        return objects;
    }

    private Class<?> getClassType(String name) throws ClassNotFoundException {
        if (name == null){
            return null;
        }
        return Class.forName(name);
    }

    private BoundSql getBoundSql(String sql){
        //标记处理类
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{","}",tokenHandler);
        //解析出来的sql
        String parseSql = parser.parse(sql);
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        return new BoundSql(parseSql,parameterMappings);
    }
}
